package org.nobody.mallb2c.mallmember.interceptor;

import org.nobody.common.constant.AuthServerConstant;
import org.nobody.common.vo.MemberRespVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 3489309323@qq.com
 * @create 2020-09-21-20:13
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {
  public static ThreadLocal<MemberRespVo> loginUser = new ThreadLocal<>();

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    System.out.println("LoginUserInterceptor preHandle~~~~");
    //比如下单时要计算运费 运费要根据用户地址来计算 也就是要调用用户模块(如果不带上cookie严明身份,只能这里放行)
    boolean match = new AntPathMatcher().match("/mallmember/**", request.getRequestURI());
    if (match) {
      return true;
    }

    MemberRespVo userInfo = (MemberRespVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
    System.out.println("userInfo: " + userInfo);
    if (userInfo != null) {
      loginUser.set(userInfo);

      return true;
    } else {
      // 没登录就去登录
      request.getSession().setAttribute("msg", "请先进行登录");
      response.sendRedirect("http://auth.mall.com/login.html");
      return false;
    }
  }
}
